# -*- coding: utf-8 -*-
import os,sys,time
import json
import requests
import urllib.request
from django.shortcuts import render
from bs4 import BeautifulSoup
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import  HttpResponse
from django.template.loader import  get_template
from math import ceil
from http import cookiejar


import re
from kalf import www
from kalf.models import Order,Product
from django.contrib.auth.hashers import make_password,check_password




# Create your views here.

def get_order_list():
    order = Order()
    datalist = order.show_order_list()
    return datalist

def get_orderlist_byDate(startdate,enddate):
    order = Order()
    datalist = order.show_order_list_bydate(startdate,enddate)
    return datalist

def get_import_orderlist():
    order =Order()
    datalist = order.show_import_orderlist()
    return datalist

def get_import_order_byconf(startdate,enddate):
    order = Order()
    datalist = order.show_import_orderlist_byconf(startdate,enddate)
    return datalist

#Ajax调用的获取数据的内容
def show_order_list(reqeust):
    str_url = reqeust.META.get('HTTP_REFERER')
    strs = re.findall('orderlist/(\w+)', str_url)
    num = reqeust.GET['rows']
    s_page = 0
    page = 0
    if len(strs) > 0:
        page = int(strs[0])
    else:
        page = 1

    if page > 1:
        s_page = page - 1
    n_page = page
    if "D1" in str_url:
        varrs = str_url.split('?')[1].split('=')
        start_date = varrs[1][0:10]
        end_date = varrs[2]
        datalist = get_orderlist_byDate(start_date,end_date)
    else:
        datalist = get_order_list()
    total_rows = len(datalist)
    total_page = ceil(total_rows / int(num))  #获取总页数
    if n_page > total_page:
        n_page = total_page
    #########################################################################
    dataset = datalist[s_page * int(num):n_page * int(num)]

    #///////////////////////////////////////////////////////#
    row_array =[]
    rows = len(dataset)
    for index in range(0,rows):
        dic_data ={}
        dic_data["order_id"]=str(index)
        dic_data["cell"] = dataset[index]
        row_array.append(dic_data)
    context={
        "page":"1",
        "total":str(rows),
        "records":str(rows),
        "rows":row_array
    }
    return HttpResponse(json.dumps(context))

def show_orderlist(request):
    str_url = request.META.get('HTTP_REFERER')
    page =1
    datalist = get_order_list()
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1

    template = get_template('orderlist.html')
    html = template.render(locals())
    return HttpResponse(html)

def show_orderlist_page(request,page):
    str_url = request.META.get('HTTP_REFERER')
    page = page
    if "D1" in request.GET:
        start_date = request.GET["D1"]
        end_date = request.GET["D2"]
        datalist = get_orderlist_byDate(start_date,end_date)
        sdate = start_date
        edate = end_date
        conf = "?D1="+start_date+"&D2="+end_date
    else:
        datalist = get_order_list()
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    template = get_template('orderlist.html')
    html = template.render(locals())
    return HttpResponse(html)

def save_order_data(request):
    data = www.getOrderInfo(request)
    list = www.getOrder(request)
    v_cnt =0
    if len(list)!=0:
        order =Order()
        for row in list:
            v_cnt += order.save_order_tmp(data,row)
    return HttpResponse(str(v_cnt))
#获取订单信息；
def getOrder(request):
    list = www.getOrder(request)
    if len(list) !=0:
        for row in list:
            p_name =row[0]
            ydsl =row[1]
            bhsl =row[2]
            dhsl =row[3]
            unit =row[4]
            print(p_name+","+ydsl+","+bhsl+","+dhsl+","+unit)
    return HttpResponse(list)

def getOrderInfo(request):
    data = www.getOrderInfo(request)
    return HttpResponse(json.dumps(data))

def getProduct(request):
    template = get_template('product.html')
    html = template.render(locals())
    return HttpResponse(html)

def get_local_producate(request):
    return www.get_local_product(request)

#绑定相应的分页变量
def show_product(request):
    product = Product()
    page =1
    datalist = product.show_product_lsit()
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    p=page
    template = get_template('productlist.html')
    html = template.render(locals())
    return HttpResponse(html)

#显示原料信息，并进行分页操作
def show_product_page(request,page):
    product = Product()
    p = page
    datalist = product.show_product_lsit()
    rows = len(datalist)
    total_page = ceil(rows/10)
    last = total_page
    next = int(page)+1
    if next > total_page:
        next = total_page
    current = int(page)-1
    if current <=0:
        current =1

    template = get_template('productlist.html')
    html = template.render(locals())
    return HttpResponse(html)

#通过切片完成分页功能
def show_product_list(request):
    str_url = request.META.get('HTTP_REFERER')
    strs = re.findall('product/(\w+)',str_url)
    num =request.GET['rows']
    s_page =0
    page =0
    if len(strs) > 0:
        page = int(strs[0])
    else:
        page =1

    if page > 1:
        s_page = page-1
    n_page = page
    product = Product()
    datalist = product.show_product_lsit()
    total_rows = len(datalist)
    total_page = ceil(total_rows / int(num))
    if n_page > total_page:
        n_page = total_page
    #########################################################################
    dataset = datalist[s_page*int(num):n_page*int(num)]
    row_array = []
    rows = len(dataset)
    for index in range(0, rows):
        dic_data = {}
        dic_data["p_id"] = str(index)
        dic_data["cell"] = dataset[index]
        row_array.append(dic_data)
    context = {
        "page": page,
        "total": str(total_rows),
        "records": str(total_rows),
        "rows": row_array
    }
    return HttpResponse(json.dumps(context))

def show_importlist(request):
    request_url ="/olist/"
    url ="olist"
    start_date = "2019-6-4" #sess.cookies['start_date']
    end_date = "2019-6-6" #sess.cookies['end_date']
    page = 1
    if len(request.COOKIES) > 0:
        datalist = get_import_order_byconf(start_date,end_date)
    else:
        datalist = get_import_orderlist()
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    template =get_template('importlist.html')
    html = template.render(locals())
    return HttpResponse(html)

def show_import_orderlist_page(request,page):
    request_url = "/olist/"
    page =page
    url = "olist"
    if "D1" in request.GET:
        start_date = request.GET["D1"]
        end_date = request.GET["D2"]
        datalist = get_import_order_byconf(start_date,end_date)
        conf = "/?D1=" + start_date + "&D2=" + end_date
        sdate = start_date
        edate = end_date
    else:
        datalist =get_import_orderlist()
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page)+1
    if next > total_page:
        next = total_page
    current = int(page) -1
    if current <=0:
        current =1
    template = get_template('importlist.html')
    html = template.render(locals())
    return HttpResponse(html)

def update_price(request):
    product =Product()
    try:
        datarow = product.show_product_lsit()
        for row in datarow:
            id = row[0]
            spec=row[3]
            sl =float(re.sub("\D","",spec))/100
            pp = float(row[5])
            price = round(pp/(sl),2)
            product.update_product_price(id,price)
    except Exception as e:
        e.args[0]
    return HttpResponse('OK')

#显示敢入的记录信息；
def show_import_orderlist(request):
    str_url = request.META.get('HTTP_REFERER')

    strs = re.findall('olist/(\w+)', str_url)
    num = 10 #request.GET['rows']
    s_page = 0
    page = 0
    if len(strs) > 0:
        page = int(strs[0])
    else:
        page = 1

    if page > 1:
        s_page = page - 1
    n_page = page
    #/////////////////////////////////////////////#
    #if  "D1" in request.GET.keys():
    if "D1" in str_url:
        strs = str_url.split('=')
        start_date =strs[1][0:10]
        end_date = strs[2]
        datalist = get_import_order_byconf(start_date,end_date)
    else:
        datalist = get_import_orderlist()
    # /////////////////////////////////////////////#
    total_rows = len(datalist)
    total_page = ceil(total_rows / int(num))
    if n_page > total_page:
        n_page = total_page
    #///////////////////////////////////////////##
    dataset = datalist[s_page * int(num):n_page * int(num)]

    row_array =[]
    rows =len(dataset)
    for index in range(0,rows):
        dic_data ={}
        dic_data["kalf_id"] =str(index)
        dic_data["cell"]=dataset[index]
        row_array.append(dic_data)
    context={
        "page":"1",
        "total":str(rows),
        "records":str(rows),
        "rows":row_array
    }
    return HttpResponse(json.dumps(context))


@csrf_exempt
def show_import_order_page(request):
    request_url = "/olist/"
    url ="olist"

    if "D1" in request.GET.keys():
        start_date = request.GET["D1"]
        end_date = request.GET["D2"]
        datalist = get_import_order_byconf(start_date, end_date)
        conf ="/?D1="+start_date+"&D2="+end_date
        sdate = start_date
        edate = end_date
    page = 1
    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    template = get_template('importlist.html')
    html = template.render(locals())
    return HttpResponse(html)


def show_import_order_page2(request,page):
    page = page
    str_url = request.META.get('HTTP_REFERER')
    #urls = str_url.split('?')
    #request_url = "/slist/"+str(page)+"/?"+urls[1]   # 这样编写页面没反应，说明有问题；
    request_url="/olist/"
    url ="olist"

    if "D1" in str_url:
        urls = str_url.split('?')[1].split('=')
        start_date = urls[1][0:10]
        end_date = urls[2]
        datalist = get_import_order_byconf(start_date, end_date)
        conf = "/?D1=" + start_date + "&D2=" + end_date
        sdate = start_date
        edate =end_date

    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    template = get_template('importlist.html')
    html = template.render(locals())
    return HttpResponse(html)
    #return HttpResponse(json.dumps(data))

@csrf_exempt
def show_import_order_page_back(request):
    start_date = "2019-6-4" #request.POST['start_date'].replace('/','-')
    end_date = "2019-6-6" #request.POST['end_date'].replace('/','-')
   # sess =requests.session()
   # sess.cookies.set('start_date',start_date)
   # sess.cookies.set('end_date',end_date)
    datalist = get_import_order_byconf(start_date,end_date)
    page = 1

    rows = len(datalist)
    total_page = ceil(rows / 10)
    last = total_page
    next = int(page) + 1
    if next > total_page:
        next = total_page
    current = int(page) - 1
    if current <= 0:
        current = 1
    template = get_template('importlist.html')
    html = template.render(locals())
    return HttpResponse(html)
